﻿using System.Collections.Generic;
using Elight.WebUI.Filters;
using Elight.Utility.ResponseModels;
using Microsoft.AspNetCore.Mvc;
using Elight.Utility.Core;
using Elight.WebUI.Controllers;
using FastReport;
using Elight.Utility.Extension;
using System.Data;
using FastReport.Export.PdfSimple;
using Elight.Utility.Other;
using System.Diagnostics;
using System;
using FastReport.Export.Html;
using System.IO;
using System.Linq;
using Elight.Utility.Files;

namespace Elight.WebUI.Areas.Base.Controllers
{
    [HiddenApi]
    [Area("Base")]
    public class PrintTestController : BaseController
    {
        [Route("/base/printTest/index")]
        [HttpGet, AuthorizeChecked]
        public ActionResult Index()
        {
            return View();
        }

        [Route("/base/printTest/index")]
        [HttpPost, AuthorizeChecked]
        public ActionResult Index(int pageIndex, int pageSize, string keyWord)
        {
            List<PrintTestData> list = GetData();
            var result = new LayPadding<PrintTestData>()
            {
                result = true,
                msg = "success",
                list = list,
                count = list.Count
            };
            return Content(result.ToJson());
        }


        [HttpPost, Route("base/printTest/print")]
        public ActionResult Print(string primaryKey)
        {
            Report report = new Report();
            report.Load(MyEnvironment.RootPath("Reports/test.frx"));//加载frx文件

            List<PrintTestData> list = GetData();
            List<PrintTestData> printData = list.Where(it => it.Id == primaryKey).ToList();
            DataTable dt = printData.ToJson().ToTable();
            dt.TableName = "data";
            //#region 造数据
            //DataTable dt = new DataTable();//数据源
            //dt.TableName = "data";
            //dt.Columns.Add("EnCode");
            //dt.Columns.Add("Name");
            //dt.Columns.Add("SortCode");
            //dt.Columns.Add("IsEnabled", typeof(bool));
            //dt.Columns.Add("Remark");
            //DataRow row = dt.NewRow();
            //row["EnCode"] = primaryKey;
            //row["Name"] = "编号" + primaryKey;
            //row["SortCode"] = primaryKey.Replace("Code", "");
            //row["IsEnabled"] = true;
            //row["Remark"] = "";
            //dt.Rows.Add(row);
            //#endregion

            report.SetParameterValue("ReportName", "报表");//设置报表参数
            report.RegisterData(dt, "data");        //注册数据
            report.Prepare();                       //准备数据
            string pdfCmdPath = MyEnvironment.RootPath("Reports/PDFtoPrinter.exe");
            string printName = @"\\print-server\漫游打印";
            string pdfPath = MyEnvironment.RootPath($"wwwroot/Uploads/{UUID.StrSnowId}.pdf");
            PDFSimpleExport export = new PDFSimpleExport();//导出文件
            report.Export(export, pdfPath);
            report.Dispose();

            //调用cmd进行打印
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            string cmd = $"{pdfCmdPath} {pdfPath} \"{printName}\"";
            p.StandardInput.WriteLine(cmd + "&exit");
            p.StandardInput.AutoFlush = true;
            string output = p.StandardOutput.ReadToEnd();
            Console.WriteLine(output);
            p.WaitForExit();
            p.Close();

            return Success();

        }


       

        [HttpGet, Route("base/printTest/printView")]
        public ActionResult PrintView(string primaryKey)
        {
            Report report = new Report();
            report.Load(MyEnvironment.RootPath("Reports/test.frx"));//加载frx文件

            List<PrintTestData> list = GetData();
            List<PrintTestData> printData = list.Where(it => it.Id == primaryKey).ToList();
            DataTable dt = printData.ToJson().ToTable();
            dt.TableName = "data";

            report.SetParameterValue("ReportName", "报表");//设置报表参数
            report.RegisterData(dt, "data");        //注册数据
            report.Prepare();                       //准备数据

            string htmlContent = "";
            using (HTMLExport html = new HTMLExport())
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    report.Export(html, stream);
                    byte[] b = stream.ToArray();
                    htmlContent = System.Text.Encoding.UTF8.GetString(b, 0, b.Length);
                }
            }
            report.Dispose();
            return Content(htmlContent, "text/html");
        }


        [HttpGet, Route("base/showpdf{primaryKey}")]
        public ActionResult ShowPDF(string primaryKey)
        {
            return Export(primaryKey);
        }

        [HttpPost, Route("base/printTest/export")]
        public ActionResult Export(string primaryKey)
        {
            Report report = new Report();
            report.Load(MyEnvironment.RootPath("Reports/test.frx"));//加载frx文件

            List<PrintTestData> list = GetData();
            List<PrintTestData> printData = list.Where(it => it.Id == primaryKey).ToList();
            DataTable dt = printData.ToJson().ToTable();
            dt.TableName = "data";

            report.SetParameterValue("ReportName", "报表");   //设置报表参数
            report.RegisterData(dt, "data");                  //注册数据
            report.Prepare();
            //准备数据 
            byte[] bytes;

            using (PDFSimpleExport export = new PDFSimpleExport())
            {
                //导出文件
                using (MemoryStream stream = new MemoryStream())
                {
                    report.Export(export, stream);
                    bytes = stream.ToArray();
                }
            }
            report.Dispose();

            return File(bytes, "application/octet-stream", $"{UUID.StrSnowId}.pdf");
        }

        [HttpPost, Route("base/printTest/exportExcel")]
        public ActionResult ExportExcel()
        {
            List<PrintTestData> list = GetData();
            Dictionary<string, string> headDict = new Dictionary<string, string>();
            headDict.Add("Id", "Id");
            headDict.Add("EnCode", "编码");
            headDict.Add("Name", "名称");
            headDict.Add("SortCode", "排序号");
            headDict.Add("IsEnabled", "是否启用");
            headDict.Add("Remark", "备注信息");
            byte[] bytes = ExcelUtils.ExportExcel(list, headDict, "测试数据", true);
            return File(bytes, "application/octet-stream", "测试数据.xlsx");
        }


        /// <summary>
        /// 造数据
        /// </summary>
        /// <returns></returns>
        private List<PrintTestData> GetData()
        {
            List<PrintTestData> list = new List<PrintTestData>();
            for (var i = 0; i < 5; i++)
            {
                list.Add(new PrintTestData
                {
                    Id = $"{i + 1}",
                    EnCode = $"{i + 1}",
                    Name = $"编号{i + 1}",
                    SortCode = i,
                    IsEnabled = true,
                    Remark = ""
                });
            }
            return list;
        }
    }

    class PrintTestData
    {
        public string Id { get; set; }
        public string EnCode { get; set; }
        public string Name { get; set; }
        public int SortCode { get; set; }
        public bool IsEnabled { get; set; }
        public string Remark { get; set; }

    }
}
